﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Windows.Threading;
using LibGreen;
using LibGreen.Events;

namespace WindowsFormsApplication1
{
	public partial class ChatRoomPanel : UserControl
	{
		public Dispatcher dis = Dispatcher.CurrentDispatcher;
		public IChatRoom channel;
		public ChatRoomPanel (IChatRoom chan)
		{
			InitializeComponent ();
			channel = chan;
			chan.MessageReceived += RecieveChatRoomMessage;
			chan.UserLeft += new LibGreen.Events.ChatRoomStatusUpdateHandler (chan_UserLeft);
			chan.UserJoined += new ChatRoomStatusUpdateHandler (chan_UserJoined);
		}

		private void chan_UserLeft (IChatRoom sess, ChatRoomStatus arg)
		{
			dis.BeginInvoke (DispatcherPriority.Input, new Action<ChatRoomStatus> (UserLeft), arg);
		}

		private void chan_UserJoined (IChatRoom sess, ChatRoomStatus arg)
		{
			dis.BeginInvoke (DispatcherPriority.Input, new Action<ChatRoomStatus> (UserJoined), arg);
		}

		private void UserLeft (ChatRoomStatus arg)
		{
			foreach (Contact con in arg.memberOfChannel){
				if (MemberList.Items.Contains (con)) {
					MemberList.Items.Remove (con);
				}
			}
		}

		private void UserJoined (ChatRoomStatus arg)
		{
			foreach (Contact con in arg.memberOfChannel) {
				if (!MemberList.Items.Contains (con)) {
					MemberList.Items.Add (con);
				}
			}
		}

		private void RecieveChatRoomMessage (IDialog room, LibGreen.Message mes)
		{
			dis.BeginInvoke(DispatcherPriority.Input, new Action<LibGreen.Message>(NewMessage), mes);
		}

		private void NewMessage (LibGreen.Message ms)
		{
			this.ChatRoomText.AppendText (ms.Sender + ":  " + ms.Text);
		}
		
		private int isShifted= 0;
		private void UserNewText_KeyDown (object sender, KeyEventArgs e)
		{
			if (e.Shift)
				isShifted++;
		}

		private void UserNewText_KeyPress (object sender, KeyPressEventArgs e)
		{

			if ((e.KeyChar == '\n' || e.KeyChar == '\r') && isShifted <= 0)
				channel.SendMessage(new LibGreen.Message(){Text = UserNewText.Text});
		}

		private void UserNewText_KeyUp (object sender, KeyEventArgs e)
		{
			if (e.Shift)
				isShifted--;
		}
	}
}
